﻿define(['admin/app', "service/baseService"], function (app) {
    "use strict";
    app.controller('appController', function ($scope, $state, baseService) {
        var profile_menu = { name: '', children: [{ name: '账户', children: [{ name: '个人资料', url: 'app.account.profile' }, { name: '修改密码', url: 'app.account.change_pwd' }] }] };
        var default_menu = { name: '首页', url: 'app.dashboard', children: [{ name: '常用功能', children: [{ name: '订单', url: 'app.order.list' }, { name: '商户', url: 'app.member.list' }, { name: '结算', url: 'app.transfer.list' }] }] };

        $scope.current = null;
        $scope.$state = $state;
        var methods = {
            logout: function () {
                location.href = '/account/logout?return_url=/#/login';
            },
            get_menus: function () {
                baseService.admin_menus().success(function (response) {
                    response.data.unshift(default_menu);
                    $scope.layout_menus = response.data;
                    if ($state.includes('app.account'))
                        $scope.current = profile_menu;
                    else {
                        var roule = $state.current.name;
                        var arrs = roule.split('.');
                        var url = arrs[0] + '.' + arrs[1];
                        var meun = $.grep(response.data, function (n, i) {
                            return n.url == url;
                        });
                        $scope.current = meun[0];
                        if ($scope.current != null) {
                            var goto_url = $scope.current.goto_url;
                            if (arrs.length == 2 && goto_url != null) {
                                var goto_url_arrs = goto_url.split('(');
                                if (goto_url_arrs.length > 1) {
                                    var goto_params = goto_url_arrs[1].split(')')[0];
                                    $state.go(goto_url_arrs[0], angular.fromJson(eval("(" + goto_params + ")")));
                                }
                                else
                                    $state.go(goto_url);
                            }
                        }
                    }
                }).error(function () { methods.logout(); });
            },
            jump: function (item) {
                $scope.current = item;
            },
            open_frist: function (roule) {
                var meun = $.grep($scope.layout_menus, function (n, i) {
                    return n.url == roule;
                });
                if (meun[0].goto_url != null) roule = meun[0].goto_url;
                return roule;
            },
            account: function () {
                $scope.current = profile_menu;
            }
        }
        methods.get_menus();
        angular.extend($scope, methods);
    });
});
